package com.meowcook.component;

import com.meowcook.exception.LoginElseException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketSession;

import java.util.concurrent.ConcurrentHashMap;

/**
 * Created with Intellij IDEA.
 * Description:
 * User: 28792
 * Date: 2025-11-15
 * Time: 15:52
 */
@Slf4j
@Component
public class OnlineUserManager {
    private static final ConcurrentHashMap<Long, WebSocketSession> onlineUserMap = new ConcurrentHashMap<>();

    // 用户上线时绑定WebSocketSession和用户id
    public void online(WebSocketSession session, Long userId) {
        if (onlineUserMap.containsKey(userId)) {
            throw new LoginElseException();
        }
        log.info("用户上线: {}", userId);
        onlineUserMap.put(userId, session);
    }

    // 2) 用户下线, 针对这个哈希表进行删除元素
    public void offline(Long userId, WebSocketSession session) {
        WebSocketSession existSession = onlineUserMap.get(userId);
        if (existSession == session) {
            // 如果这俩 session 是同一个, 才真正进行下线操作. 否则就啥都不干
            onlineUserMap.remove(userId);
            log.info("用户下线: {}", userId);
        }
    }

    // 3) 根据 userId 获取到 WebSocketSession
    public WebSocketSession getSession(Long userId) {
        return onlineUserMap.get(userId);
    }

}
